package com.zsd.android.bsdiffdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.zsd.android.bsdiffdemo.utils.MLog;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv = findViewById(R.id.sample_text);
        tv.setText(BuildConfig.VERSION_NAME);
        findViewById(R.id.update_btn).setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String perms[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (checkSelfPermission(perms[0]) == PackageManager.PERMISSION_DENIED) {
                requestPermissions(perms, 200);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.update_btn:
                update();
                break;
        }
    }

    private void update() {
        String patch = new File(Environment.getExternalStorageDirectory(), "patch").getAbsolutePath();
//      String oldApk = getApplicationInfo().sourceDir;
        String oldApk = getApplicationContext().getPackageResourcePath();
        MLog.i("patch = " + patch + ", oldApk = " + oldApk);
        String output = new File(Environment.getExternalStorageDirectory(), "new.apk").getAbsolutePath();
        bsPatch(oldApk, patch, output);
        installApk(output);
    }

    private void installApk(String output) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(this,"com.zsd.android.bsdiffdemo.fileprovider",new File(output));
            intent.setDataAndType(uri,"application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.parse("file://" + output),"application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    public native String stringFromJNI();

    /**
     * 合成安装包
     * @param oldApk 旧版本apk路径
     * @param patch 差分包，patch文件路径
     * @param output 合成后新版本路径
     */
    public native void bsPatch(String oldApk, String patch, String output);
}
